<template>
  <a-table
    rowKey="id"
    size="middle"
    bordered
    :loading="loading"
    :columns="columns"
    :dataSource="tableDataWithTotal"
    :pagination="false"
  >
    <template slot="htmlSlot" slot-scope="text">
      <div v-html="text"></div>
    </template>

    <template slot="imgSlot" slot-scope="text,record">
      <div style="font-size: 12px;font-style: italic;">
        <span v-if="!text">无图片</span>
        <img v-else :src="getImgView(text)" :preview="record.id" alt="" style="max-width:80px;height:25px;"/>
      </div>
    </template>

    <template slot="fileSlot" slot-scope="text">
      <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
      <a-button
        v-else
        ghost
        type="primary"
        icon="download"
        size="small"
        @click="downloadFile(text)"
      >
        <span>下载</span>
      </a-button>
    </template>
  </a-table>
</template>

<script>
import { getAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'CwLxrygzjbxmxbSubTable',
  mixins: [JeecgListMixin],
  props: {
    record: {
      type: Object,
      default: null,
    }
  },
  data() {
    return {
      description: '离休人员工资及保险明细表内嵌列表',
      disableMixinCreated: true,
      loading: false,
      dataSource: [],
      // 所有需要计算合计的字段（dataIndex集合，共23个）
      totalFields: [
        'jblxf', 'nqzj', 'nhzj', 'npzjdshf', 'dsznjf', 'lxshbt', 'jf', 'jlm',
        'tsgwjt', 'wsf', 'tgjf', 'lmyyjt', 'nzjdshbt', 'nursingFee', 'zfjzbt',
        'zjjblxf', 'yyffgzhj', 'njfgz', 'nyfgzhj', 'ylbxjs', 'ylbx', 'heatingFee', 'yjsbfhzj'
      ],
      columns: [
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '年度',
          align: 'center',
          dataIndex: 'year_dictText'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
        },
        {
          title: '职务（职称）',
          align: 'center',
          dataIndex: 'zc',
        },
        {
          title: '基本离退休费',
          align: 'center',
          dataIndex: 'jblxf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '06年前增加的生活费',
          align: 'center',
          dataIndex: 'nqzj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '06年后增加的生活费',
          align: 'center',
          dataIndex: 'nhzj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2021年增加的生活费（工资补贴）',
          align: 'center',
          dataIndex: 'npzjdshf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '独生子女加发5%',
          align: 'center',
          dataIndex: 'dsznjf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '离休生活补贴',
          align: 'center',
          dataIndex: 'lxshbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '加发5%补贴',
          align: 'center',
          dataIndex: 'jf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '教龄满30年加发',
          align: 'center',
          dataIndex: 'jlm',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '特殊岗位津贴',
          align: 'center',
          dataIndex: 'tsgwjt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '卫生费',
          align: 'center',
          dataIndex: 'wsf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '特贡加发',
          align: 'center',
          dataIndex: 'tgjf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '劳模荣誉津贴',
          align: 'center',
          dataIndex: 'lmyyjt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2021年增加的生活补贴',
          align: 'center',
          dataIndex: 'nzjdshbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '护理费',
          align: 'center',
          dataIndex: 'nursingFee',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '住房提租补贴',
          align: 'center',
          dataIndex: 'zfjzbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2024年增加基本离休费',
          align: 'center',
          dataIndex: 'zjjblxf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '月应发工资合计',
          align: 'center',
          dataIndex: 'yyffgzhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '年加发工资',
          align: 'center',
          dataIndex: 'njfgz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '年应发工资合计',
          align: 'center',
          dataIndex: 'nyfgzhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '养老保险基数（年）',
          align: 'center',
          dataIndex: 'ylbxjs',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '养老保险（72%）',
          align: 'center',
          dataIndex: 'ylbx',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '取暖费',
          align: 'center',
          dataIndex: 'heatingFee',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '预计社保返还资金',
          align: 'center',
          dataIndex: 'yjsbfhzj',
          customRender: (text) => this.formatNumber(text)
        },
      ],
      url: {
        listByMainId: '/cw/cwLxrygzjbxmxbTj/queryCwLxrygzjbxmxbByMainId',
      },
    }
  },
  computed: {
    // 带合计行的完整数据
    tableDataWithTotal() {
      if (!this.dataSource || this.dataSource.length === 0) return []

      // 深拷贝原始数据，避免污染原数据
      const newData = JSON.parse(JSON.stringify(this.dataSource))
      // 计算所有字段合计
      const fieldTotals = this.calcAllFieldTotals()

      // 构建合计行
      const totalRow = {
        id: 'total_' + new Date().getTime(), // 唯一ID，避免rowKey重复警告
        name: '合计',
        year_dictText: '',
        unit: '',
        zc: '',
        // 填充所有合计字段值
        jblxf: fieldTotals.jblxf,
        nqzj: fieldTotals.nqzj,
        nhzj: fieldTotals.nhzj,
        npzjdshf: fieldTotals.npzjdshf,
        dsznjf: fieldTotals.dsznjf,
        lxshbt: fieldTotals.lxshbt,
        jf: fieldTotals.jf,
        jlm: fieldTotals.jlm,
        tsgwjt: fieldTotals.tsgwjt,
        wsf: fieldTotals.wsf,
        tgjf: fieldTotals.tgjf,
        lmyyjt: fieldTotals.lmyyjt,
        nzjdshbt: fieldTotals.nzjdshbt,
        nursingFee: fieldTotals.nursingFee,
        zfjzbt: fieldTotals.zfjzbt,
        zjjblxf: fieldTotals.zjjblxf,
        yyffgzhj: fieldTotals.yyffgzhj,
        njfgz: fieldTotals.njfgz,
        nyfgzhj: fieldTotals.nyfgzhj,
        ylbxjs: fieldTotals.ylbxjs,
        ylbx: fieldTotals.ylbx,
        heatingFee: fieldTotals.heatingFee,
        yjsbfhzj: fieldTotals.yjsbfhzj
      }

      newData.push(totalRow)
      return newData
    }
  },
  watch: {
    record: {
      immediate: true,
      handler() {
        if (this.record) {
          this.loadData(this.record)
        }
      }
    }
  },
  methods: {
    loadData(record) {
      this.loading = true
      this.dataSource = []
      getAction(this.url.listByMainId, { id: record.id })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [] // 兼容无数据场景
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 数字格式化通用方法（默认保留2位小数，适配金额字段）
     * @param text 原始值
     * @param decimal 小数位数（默认2位）
     */
    formatNumber(text, decimal = 2) {
      const num = Number(text)
      // 处理非数字情况，返回对应格式的0值
      return isNaN(num) ? `0.${'0'.repeat(decimal)}` : num.toFixed(decimal)
    },

    /**
     * 批量计算所有目标字段的合计
     */
    calcAllFieldTotals() {
      // 初始化所有合计字段为0
      const totals = this.totalFields.reduce((obj, field) => {
        obj[field] = 0
        return obj
      }, {})

      // 遍历数据累加每个字段值（处理空值和非数字）
      this.dataSource.forEach(item => {
        this.totalFields.forEach(field => {
          const val = Number(item[field])
          totals[field] += isNaN(val) ? 0 : val
        })
      })

      // 格式化所有合计结果（统一保留2位小数）
      this.totalFields.forEach(field => {
        totals[field] = totals[field].toFixed(2)
      })

      return totals
    },

    // 空实现方法，避免报错（保持与Jeecg模板结构一致）
    downloadFile(text) {
    },
    getImgView(text) {
      return text
    }
  },
}
</script>

<style scoped>
/* 合计行样式优化，突出显示且适配多列表格 */
::v-deep .ant-table-tbody tr:last-child {
  background-color: #f5fafe !important;
}

::v-deep .ant-table-tbody tr:last-child td {
  font-weight: 600 !important;
  border-top: 2px solid #64b5f6 !important;
  color: #2196f3 !important;
  text-align: center !important;
  white-space: nowrap !important;
}

/* 表格横向滚动和列宽优化，避免多列挤压 */
::v-deep .ant-table-container {
  overflow-x: auto !important;
  min-width: 1300px !important;
}

::v-deep .ant-table-column-title {
  white-space: nowrap !important;
  font-size: 12px !important;
}

/* 数据单元格样式优化，提升可读性 */
::v-deep .ant-table-tbody td {
  white-space: nowrap !important;
  font-size: 12px !important;
}
</style>